package com.kx.demo.concurrent;

import java.util.LinkedList;

/**
 * @author kx
 */
public class CustomQueue<V> {

    private final int MAX_SIZE = 5;
    private LinkedList<V> queue = new LinkedList<>();

    public synchronized void put(V item) {
        if (queue.size() == MAX_SIZE) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        queue.add(item);
        System.out.println("放入元素" + item);
        notify();
    }

    public synchronized void pop() {
        if (queue.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("弹出元素" + queue.pop());
        notify();
    }

    public static void main(String[] args) throws InterruptedException {
        CustomQueue<String> queue = new CustomQueue<>();

        Thread putThread = new Thread(() -> {
            int i = 0;
            while (true) {
                i++;
                queue.put(String.valueOf(i));
            }
        });

        Thread popThread = new Thread(() -> {
            while (true) {
                try {
                    queue.pop();
                    Thread.sleep(1 * 3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        putThread.start();
        popThread.start();
        putThread.join();
        popThread.join();
    }

}
